/*
 Using the support list to calculate the confidence for each pair of large item set.
 */
package Apriori;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Collections;

/**
 * @author Yilin/YichaoSun
 */
public class CalcConfidence {
    
    private HashMap<AssoRule,Double> resultSets = new HashMap<AssoRule,Double>();
    private HashMap<ArrayList<String>, Integer> largeItemSet = new HashMap<ArrayList<String>, Integer>();
    private double minConf;
    
    public CalcConfidence(HashMap<ArrayList<String>, Integer> largeItemSet, double minConf){
        this.largeItemSet = largeItemSet;
        this.minConf = minConf;
        CalcRules();
    }
    
    private void CalcRules(){
        Iterator<ArrayList<String>> singleItemSetiter = largeItemSet.keySet().iterator();
        while(singleItemSetiter.hasNext()){
            ArrayList<String> singleItemSet = singleItemSetiter.next();
            ArrayList<ArrayList<String>> subSets = new ArrayList<ArrayList<String>>();
            
            //Find all subsets
            ArrayList<String> tempSubSet = new ArrayList<String>();
            for( int m=0; m< singleItemSet.size(); m++){
                for( int n=0; n<m; n++){
                    for( int k=n; k<m; k++){
                        tempSubSet.add(singleItemSet.get(k));
                    }
                    subSets.add(tempSubSet);
                    tempSubSet.clear();
                }
            }
            
            for( int j=0; j<subSets.size(); j++){
                double tmpValue = (largeItemSet.get(subSets.get(j)))/(largeItemSet.get(singleItemSet));
                if (tmpValue > minConf){
                   ArrayList<String> RHS = new ArrayList<String>();
                   ArrayList<String> LHS = new ArrayList<String>();
		   Iterator<String> tmpIter = singleItemSet.iterator();
                   while(tmpIter.hasNext()){
                       String item = tmpIter.next();
                       if(!subSets.get(j).contains(j)){
                           RHS.add(item);
                           Collections.sort(RHS);
                           AssoRule tempRule = new AssoRule(subSets.get(j), RHS);
                           resultSets.put(tempRule, tmpValue);
                                   
                       }
                   }			
                }
            }
            
            
        }
    }
    
    public HashMap<AssoRule, Double> GetRules(){
        return resultSets;
    }  
}
